const request = require('../../utils/request')

Page({
  data: {
    myUserId: '',
    devMac: ''
  },
  onLoad(opt) {
    this.data.myUserId = opt.userid
    this.data.devMac = opt.devMac
    console.log(opt);
    this.setData({
      devMac: this.data.devMac
    })
  },
  formSubmit(e) {
    let devMac = e.detail.value.devMacInput
    let belongToAcc = e.detail.value.belongToAcc
    console.log(e);
    if (devMac && belongToAcc) {
      this.bandShowActionSheetForInput(devMac, belongToAcc)
    } else {
      this.errorResult('参数不完整')
    }
  },

  openCameraBandDev() {
    let _this = this
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        let devName = res.result
        if (devName) {
          _this.bandShowActionSheetForScan(devName)
        }
      }
    })
  },

  bandShowActionSheetForInput(devMac, belongToAcc) {
    let _this = this
    wx.showModal({
      title: '提示',
      content: '你将会绑定设备：' + devMac,
      success(res) {
        if (res.confirm) {
            let user = {
              userId: _this.data.myUserId,
              devMac: devMac,
              accountNumber: belongToAcc
            }
          _this.bandUserAndDev(user)
        } else if (res.cancel) {}
      }
    })
  },

  bandShowActionSheetForScan(devMac) {
    let _this = this
    wx.showModal({
      editable: true,
      title: '请输入 ' + devMac + ' 的所属账号',
      success(res) {
        if (res.confirm) {
          if (res.content) {
            let user = {
              userId: _this.data.myUserId,
              devMac: devMac,
              accountNumber: res.content
            }
            _this.bandUserAndDev(user)
          } else {
            this.errorResult('请输入所属账号')
          }
        } else if (res.cancel) {}
      }
    })
  },

  bandUserAndDev(user) {
    let _this = this
    request.post('/bandUserAndDev', user).then(res2 => {
      if (Number(res2.code) === 0) {
        // 绑定成功
        this.cleanInputText()
        _this.successResult('绑定成功')
      } else {
        this.cleanInputText()
        _this.errorResult(res2.msg)
      }
    })
  },

  cleanInputText() {
    this.setData({
      devMac: '',
      devAcc: ''
    })
  },

  errorResult(errorInfo) {
    wx.showToast({
      title: errorInfo,
      icon: 'error',
      duration: 2000
    })
  },

  successResult(successInfo) {
    wx.showToast({
      title: successInfo,
      icon: 'success',
      duration: 2000
    })
  },

  back() {
    wx.navigateBack({
      delta: 1,
    });
  },

})